package com.css.zfzx.sjcj.modules.statistics.hdcActiveFault.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.zfzx.sjcj.common.Constant;
import com.css.zfzx.sjcj.common.utils.CheckObjFields;
import com.css.zfzx.sjcj.common.utils.ProvinceCityAreaUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.common.vo.DivisionVo;
import com.css.zfzx.sjcj.modules.pojo.PcStatisticsFillVO;
import com.css.zfzx.sjcj.modules.pojo.QueryVo;
import com.css.zfzx.sjcj.modules.statistics.dao.primary.SuperDao;
import com.css.zfzx.sjcj.modules.statistics.hdcActiveFault.repository.HdcActiveFaultNativeRepository;
import com.css.zfzx.sjcj.modules.statistics.hdcActiveFault.repository.entity.HddcActivefaultEntity;
import com.css.zfzx.sjcj.modules.statistics.hdcActiveFault.repository.entity.HddcActivefaultVO;
import com.css.zfzx.sjcj.modules.statistics.hdcActiveFault.service.HdcActiveFaultService;
import com.css.zfzx.sjcj.modules.sys.usersInfo.UsersVo;
import com.css.zfzx.sjcj.modules.sys.usersInfo.repository.UsersInfoRepository;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class HdcActiveFaultServiceImpl implements HdcActiveFaultService {
    @Autowired
    private HdcActiveFaultNativeRepository nativeRepository;
    @Autowired
    private SuperDao superDao;
    @Autowired
    UsersInfoRepository usersInfoRepository;
    List<UsersVo> usersVoList = new ArrayList<>();
    List<Integer> featureids= new ArrayList<>();
    List<Integer> lastnewids= new ArrayList<>();
    @PostConstruct
    public void init(){
        usersVoList = usersInfoRepository.getAll();
        initFeatureIds();
        initNewIds();
    }
    @Override
    public List<PcStatisticsFillVO> findCreateTime(LocalDateTime createTime) {
        List<PcStatisticsFillVO> entities = nativeRepository.findCreateTime(createTime);
        return entities;
    }

    @Override
    public List<PcStatisticsFillVO> findUpdateTime(LocalDateTime updateTime) {
        List<PcStatisticsFillVO> entities = nativeRepository.findUpdateTime(updateTime);
        return entities;
    }

    @Override
    public List<DivisionVo> count(int identify) {
        return nativeRepository.count(identify);
    }

    /**
     * 库里所有试点县区划的集合
     * String  区划编码
     */
    public static List<String> pioneerCodeList = Arrays.asList(Constant.pioneerCodeList);
    @Override
    public JSONObject find(QueryVo queryVo, String userId, int curPage, int pageSize, String sort, String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0) {
            sort = CheckObjFields.propertyChange(sort);
        }
        Page<HddcActivefaultVO> hddcActivefaultVOS = nativeRepository.find(queryVo, userId, curPage, pageSize, sort, order);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", getVOs(userId, hddcActivefaultVOS.getContent()));
        jsonObject.put("total", hddcActivefaultVOS.getTotalElements());
        return jsonObject;
    }

    @Override
    public void export(String userId, HttpServletResponse resp) {
        OutputStream out = null;
        try {
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String name = dateStr + "活动断层-线.xlsx";
            //resp.setContentType("application/octet-stream ");
            resp.setHeader("content-Type", "application/vnd.ms-excel");
            resp.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            //resp.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            resp.setHeader("Content-Disposition", "attachment;fileName="
                    + new String(name.getBytes("GB2312"), "ISO8859-1"));
            resp.setCharacterEncoding("UTF-8");

            XSSFWorkbook workbook = new XSSFWorkbook();// 创建一个Excel文件
            // 样式设置
            XSSFCellStyle columnHeadStyle = workbook.createCellStyle();
            columnHeadStyle.setFillPattern(FillPatternType.NO_FILL); // 背景
            columnHeadStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); // 背景色AQUA.getIndex()
            columnHeadStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            columnHeadStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            columnHeadStyle.setBorderTop(BorderStyle.THIN);// 上边框
            columnHeadStyle.setBorderRight(BorderStyle.THIN);// 右边框
            columnHeadStyle.setAlignment(HorizontalAlignment.CENTER);//左右居中
            columnHeadStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);// 上下居中
            columnHeadStyle.setWrapText(true);//自动换行

            XSSFSheet sheet = workbook.createSheet("活动断层-线");
            String[] sheetHeadTitle = new String[]{"省", "市", "区(县)", "上传人", "上传时间", "是否上报pg库", "最新活动年代", "活动断层编号", "活动断层名称", "活动断层类型","空间属性"};
            ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            List<HddcActivefaultVO> vOs = getVOs(userId, nativeRepository.findNoPage(userId));
            List<HddcActivefaultVO> hddcActivefaultVOS = new ArrayList<>();
            for (HddcActivefaultVO vo:vOs){
                String code = ProvinceCityAreaUtil.getCode(vo.getProvince(), vo.getCity(), vo.getArea());
                if (!pioneerCodeList.contains(code)) {
                    String cityCode=code.substring(0, 4) + "00";
                    if (!pioneerCodeList.contains(cityCode)){
                        continue;
                    }
                }
                hddcActivefaultVOS.add(vo);
            }
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, sheetHeadTitle.length - 1));
            for (int i = 0; i < hddcActivefaultVOS.size() + 2; i++) {
                XSSFRow row0 = sheet.createRow(i);
                row0.setHeightInPoints(30);
                String[] values =null;
                if (i>1){
                    values = CheckObjFields.objectChangeArray(hddcActivefaultVOS.get(i - 2));
                }
                for (int t = 0; t < sheetHeadTitle.length; t++) {
                    XSSFCell cel0_i = row0.createCell(t);
                    if (i == 0 && t == 0) {
                        cel0_i.setCellValue(new XSSFRichTextString("活动断层-线"));
                    } else if (i == 1) {
                        cel0_i.setCellValue(new XSSFRichTextString(sheetHeadTitle[t]));
                    } else if (i > 1) {
                        if (t==sheetHeadTitle.length-1){
                            cel0_i.setCellValue(new XSSFRichTextString("矢量线"));
                        }else {
                            if (t==5){
                                if ("1".equals(values[t])){
                                    cel0_i.setCellValue(new XSSFRichTextString("已上报"));
                                }else {
                                    cel0_i.setCellValue(new XSSFRichTextString("未上报"));
                                }
                            }else {
                                if (StringUtils.isEmpty(values[t])||"null".equals(values[t])){
                                    cel0_i.setCellValue(new XSSFRichTextString());
                                }else {
                                    cel0_i.setCellValue(new XSSFRichTextString(values[t]));
                                }
                            }
                        }
                    }
                    cel0_i.setCellStyle(columnHeadStyle);
                    //sheet.autoSizeColumn((short) t);//宽度自适应
                }
                sheet.setColumnWidth(i, 6000);
            }
            out = resp.getOutputStream();
            workbook.write(out);
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // workbook.write(bos);
            // bos.writeTo(out);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private List<HddcActivefaultVO> getVOs(String userId, List<HddcActivefaultVO> list) {
        for (HddcActivefaultVO vo: list){
            vo.setSpaceType("矢量线");
            for (UsersVo usersVo:usersVoList){
                String usersId = usersVo.getUsersId();
                if (usersId.equals(vo.getCreateUser())){
                    vo.setCreateUser(usersVo.getUsersName());
                    break;
                }
                if (usersId.equals(userId)){
                    vo.setCreateUser(usersVo.getUsersName());
                    break;
                }
            }
        }
        return list;
    }

    @Override
    public void dataQualityCheck(QueryVo queryVo) {
        List<HddcActivefaultEntity> noPage = nativeRepository.findNoPages(queryVo, null);
        List<HddcActivefaultEntity> updateList=new ArrayList<>();
        try {
            for (HddcActivefaultEntity vo : noPage) {
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);
                ServerUtil.checkFieldNull(vo, methods, errorMsg);

                if (vo.getFeature()!=null) {
                    if (!featureids.contains(vo.getFeature())) {
                        ServerUtil.addErrorMsg(errorMsg, "feature", "活动断层类型不符合规范");
                    }
                }
                if (vo.getLatestactiveperiod()!=null) {
                    if (!lastnewids.contains(vo.getLatestactiveperiod())) {
                        ServerUtil.addErrorMsg(errorMsg, "latestactiveperiod", "最新活动年代不符合规范");
                    }
                }
                if (StringUtils.isNotEmpty(String.valueOf(errorMsg)) && errorMsg.length() > 0) {
                    vo.setQualityStatus("2");
                    vo.setQualityComment(String.valueOf(errorMsg));
                }else {
                    vo.setQualityStatus("1");
                    vo.setQualityComment(null);
                }
                updateList.add(vo);
            }
            superDao.batchUpdate(updateList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downAttach(String userId, HttpServletResponse resp,String id) {
        OutputStream out = null;
        try {
            String attach = nativeRepository.getIsValidAndUuid(id);
            String path ="活动断层-线.xlsx";
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            resp.reset();
            // 设置response的Header
            resp.setContentType("application/octet-stream ");
            //resp.setHeader("content-Type", "application/vnd.ms-excel");
            resp.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            //resp.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            resp.setHeader("Content-Disposition", "attachment;fileName="
                    + new String(filename.getBytes("GB2312"), "ISO8859-1"));
            resp.setCharacterEncoding("UTF-8");
            out = resp.getOutputStream();
            out.write(buffer);
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setCheckFields(Map<String, String> methods) {
        methods.put("id", "活动断层编号");
        methods.put("name", "活动断层名称");
        methods.put("feature", "活动断层类型");
        methods.put("latestactiveperiod", "最新活动年代");
    }

    private void initFeatureIds(){
        featureids.clear();
        featureids.add(111100);
        featureids.add(111101);
        featureids.add(111104);
        featureids.add(111102);
        featureids.add(111103);
        featureids.add(111110);
        featureids.add(111115);
        featureids.add(111116);
        featureids.add(111111);
        featureids.add(111112);
        featureids.add(111113);
        featureids.add(111120);
        featureids.add(111121);
        featureids.add(111122);
        featureids.add(111123);
        featureids.add(111125);
        featureids.add(111126);
        featureids.add(111127);
        featureids.add(111200);
        featureids.add(111201);
        featureids.add(111202);
        featureids.add(111203);
        featureids.add(111210);
        featureids.add(111211);
        featureids.add(111212);
        featureids.add(111213);
        featureids.add(111220);
        featureids.add(111221);
        featureids.add(111222);
        featureids.add(111223);
        featureids.add(111300);
        featureids.add(111301);
        featureids.add(111302);
        featureids.add(111303);
        featureids.add(111310);
        featureids.add(111311);
        featureids.add(111312);
        featureids.add(111313);
        featureids.add(111320);
        featureids.add(111321);
        featureids.add(111322);
        featureids.add(111323);
    }

    private void initNewIds(){
        lastnewids.clear();
        lastnewids.add(33320000);
        lastnewids.add(33320300);
        lastnewids.add(33320200);
        lastnewids.add(33310300);
        lastnewids.add(33310302);
        lastnewids.add(33310301);
        lastnewids.add(33310200);
        lastnewids.add(33310100);
        lastnewids.add(33310000);
        lastnewids.add(33300000);
        lastnewids.add(33310120);
        lastnewids.add(-33300000);
        lastnewids.add(33220000);
        lastnewids.add(33210000);
        lastnewids.add(33130000);
        lastnewids.add(33120000);
        lastnewids.add(33110000);
        lastnewids.add(33200000);
        lastnewids.add(33100000);
        lastnewids.add(33000000);
        lastnewids.add(32300000);
        lastnewids.add(32200000);
        lastnewids.add(32100000);
        lastnewids.add(32000000);
        lastnewids.add(31600000);
        lastnewids.add(31500000);
        lastnewids.add(31400000);
        lastnewids.add(31300000);
        lastnewids.add(31200000);
        lastnewids.add(31100000);
        lastnewids.add(31000000);
        lastnewids.add(23300000);
        lastnewids.add(20000000);
        lastnewids.add(10000000);
        lastnewids.add(-31100000);
    }
}
